package controller;

import model.Page;
import model.Type;
import service.GoodsService;
import service.TypeService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "GoodsListByType", value = "/goods_list")
public class GoodsListByTypeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        GoodsService gs = new GoodsService();
        String typeID1 = req.getParameter("typeid");
        int typeID = 0;
        if (typeID1 != null) {
            typeID = Integer.parseInt(typeID1);
        }
        int pageNumber = 1;
        if (req.getParameter("pageNumber") != null) {
            pageNumber = Integer.parseInt(req.getParameter("pageNumber"));
        }
        Page p = new Page();
        if (pageNumber <= 0) pageNumber = 1;
        try {
            p = gs.selectPageByTypeID(typeID, pageNumber);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (p.getTotalPage() == 0) {
            p.setPageNumber(1);
            p.setTotalPage(1);
        } else {
            if (pageNumber >= p.getTotalPage() + 1) {
                try {


                    p = gs.selectPageByTypeID(typeID, p.getTotalPage());
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        //判断是否是全部系列 不是的话就获取一下点击的系列的名字
        if (typeID != 0) {
            TypeService ts = new TypeService();
            Type type = ts.getTypeNameById(typeID);
            req.setAttribute("k", type);
        }

        req.getSession().setAttribute("p", p);
        req.getSession().setAttribute("id", String.valueOf(typeID));
        req.getRequestDispatcher("goods_list.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
